package com.bw.lib_avcore;

import android.media.MediaCodec;
import android.util.Log;
import android.view.SurfaceHolder;

import java.io.IOException;
import java.lang.reflect.Array;
import java.nio.ByteBuffer;
import java.util.Arrays;

/**
 * @author ytx
 * @date 2025-10-24 09:16
 * @description 发布视频
 */
public class MediaPublisher {
    public static final String TAG = "MediaPublisher";

    private Config mConfig;
    private VideoHelper mVideoHelper; //视频采集帮助类
    private MediaEncoder mMediaEncoder;//音视频编码器

    private VideoHelper.Params mVideoParams;

    private MediaPublisher(Config config){
        this.mConfig = config;
    }
    private volatile static MediaPublisher instance;
    public static MediaPublisher getInstance(Config config){
        if(instance == null){
            synchronized (MediaPublisher.class){
                if(instance == null){
                    instance = new MediaPublisher(config);
                }
            }
        }
        return instance;
    }

    /**
     * 初始化
     */
    public void init(){
        mVideoHelper = VideoHelper.getInstance(mConfig);
        mMediaEncoder = MediaEncoder.getInstance(mConfig);
        setCallBacks();
    }

    /**
     * 初始化视频采集
     */
    public void initVideoGather(SurfaceHolder surfaceHolder){
        mVideoParams =  mVideoHelper.initCamera(surfaceHolder);
    }

    /**
     * 初始化编码器
     */
    public void initEncoders(){
        try {
            mMediaEncoder.initVideoEncoder(mVideoParams.width, mVideoParams.height);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 开始编码
     */
    public void  startEncoder(){
        mMediaEncoder.startVideoEncode();
    }

    /**
     * 停止编码
     */
    public void stopEncoder(){
        mMediaEncoder.stopVideoEncode();
    }

    public void release(){
        mVideoHelper.release();
        mMediaEncoder.releaseVideoEncoder();
    }










    public void setCallBacks(){
        //摄像头采集--->编码器
        mVideoHelper.setCallback(new VideoHelper.Callback() {
            @Override
            public void onReceive(byte[] data, int colorFormat) {
                Log.d(TAG, "摄像头采集回调: "+ Arrays.toString(data));
                mMediaEncoder.putVideoData(data);
            }
        });
        //编码器的回调
        mMediaEncoder.setCallback(new MediaEncoder.Callback() {
            @Override
            public void outputVideoData(ByteBuffer bb, MediaCodec.BufferInfo info) {
                Log.d(TAG, "视频编码后的数据: "+ bb.toString());
                //RTMP推流
            }

            @Override
            public void outputAudioData(ByteBuffer bb, MediaCodec.BufferInfo info) {

            }
        });
    }
}
